package xin.mydreams.mybill.widget.user.controller;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import xin.mydreams.mybill.global.result.GetFormatResult;
import xin.mydreams.mybill.global.result.PostFormatResult;
import xin.mydreams.mybill.global.result.exception.MyException;
import xin.mydreams.mybill.util.CodeUtil;
import xin.mydreams.mybill.util.FileUtil;
import xin.mydreams.mybill.util.MD5Util;
import xin.mydreams.mybill.util.UserUtil;
import xin.mydreams.mybill.widget.user.entity.User;
import xin.mydreams.mybill.widget.user.service.IUserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

@RestController
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private IUserService userService;

    /**
     * 修改密码
     *
     * @param oldPassword
     * @param newPassword
     * @param newPasswordAgain
     * @return
     */
    @PostFormatResult(value = "/changePassword")
    public Object changePassword(@RequestParam(value = "oldPassword") String oldPassword,
                                 @RequestParam(value = "newPassword") String newPassword,
                                 @RequestParam(value = "newPasswordAgain") String newPasswordAgain) {
        User user = UserUtil.getUser();
        String salt = user.getSalt();
        if (StringUtils.isBlank(oldPassword) || StringUtils.isBlank(newPassword) || StringUtils.isBlank(newPasswordAgain)) {
            throw new MyException("任意密码不能为空");
        }
        oldPassword = UserUtil.getEncryptPsw(oldPassword, salt);
        if (!user.getPassword().equals(oldPassword)) {
            throw new MyException("旧密码输入错误");
        }
        if (!newPassword.equals(newPasswordAgain)) {
            throw new MyException("两次密码输入不一致");
        }

        user = userService.findByUserName(user.getUserName());
        salt = UUID.randomUUID().toString();
        user.setSalt(salt);
        user.setPassword(UserUtil.getEncryptPsw(newPasswordAgain, salt));
        user = userService.save(user);

//退出
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return user;
    }


    /**
     * 上传头像
     *
     * @param photo
     * @return
     */
    @PostFormatResult("/upload")
    public Object upload(@RequestParam(value = "photo") MultipartFile photo) {
        //获取文件名
        String fileName = photo.getOriginalFilename();
        //获取文件后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        try {
            //重新生成文件名
            fileName = MD5Util.getMessageDigest(photo.getBytes()) + suffixName;
            //将图片保存到static文件夹里
            photo.transferTo(new File(FileUtil.getPhotoPath(), fileName));
            String userName = UserUtil.getUser().getUserName();
            User user = userService.findByUserName(userName);
            user.setPhotoUrl(fileName);
            user =userService.save(user);
            return user;
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyException("上传失败：", e);
        }
    }


    /**
     * 展示头像
     *
     * @param request
     * @param response
     */
    @GetFormatResult("/showPhoto/{photoName}")
    public void showImg(@PathVariable(value = "photoName") String photoName,
                        HttpServletRequest request, HttpServletResponse response) {
        String photoPath = FileUtil.getPhotoPath();
        File imgFile = new File(photoPath, photoName);

        try (OutputStream output = response.getOutputStream();
             FileInputStream fin = new FileInputStream(imgFile);) {

            byte[] arr = new byte[1024 * 10];
            int n;
            while ((n = fin.read(arr)) != -1) {
                output.write(arr, 0, n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
